package org.wjw.auth.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.wjw.auth.WjwPermission;
import org.wjw.auth.mapper.PermissionMapper;
import org.wjw.base.util.LoginMap;
import org.wjw.org.domain.Employee;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Component
public class PermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        System.out.println("token");
        System.out.println(token);
        if(token==null){
            response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }
        Employee employee =(Employee)LoginMap.loginMap.get(token);
        System.out.println("employee");
        System.out.println(employee);
        if(employee==null){
            response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod=(HandlerMethod)handler;
            WjwPermission annotation = handlerMethod.getMethod().getAnnotation(WjwPermission.class);
            if(!Objects.nonNull(annotation)){
                return true;
            }
            List<String> sns=permissionMapper.selectPermissonsByEmployeeId(employee.getId());
            System.out.println("sns");
            System.out.println(sns);
            System.out.println(handlerMethod.getMethod().getDeclaringClass().getSimpleName() + ":" + handlerMethod.getMethod().getName());
            if(!sns.contains(handlerMethod.getMethod().getDeclaringClass().getSimpleName()+":"+handlerMethod.getMethod().getName())){
                response.getWriter().write("{\"success\":false,\"message\":\"noPermission\"}");
                return false;
            }
        }
        return true;
    }
}
